﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using blackhouse.BlackApart.Data;
using blackhouse.AsyncMail.Business;
using blackhouse.AsyncMail.Business.Data;
using System.Globalization;
using System.Net.Mail;

namespace blackhouse.BlackApart.Business.Newsletter {
    public class DaSubscriber : ISubscriber {

        #region Fields

        private ImpSubscriber instance;
        private INewsletterDataAccess data;

        #endregion

        #region Properties

        public string Email {
            get { return this.instance.Email; }
            set { this.instance = new ImpSubscriber(value); }
        }

        public Guid UniqueId {
            get { return this.instance.UniqueId; }
            set { this.instance.UniqueId = value; }
        }

        #endregion

        #region Constructors

        public DaSubscriber(INewsletterDataAccess dataAccess, string email, Guid uniqueId) {
            this.Email = email;
            this.UniqueId = uniqueId;
            this.data = dataAccess;
        }

        public DaSubscriber(INewsletterDataAccess dataAccess, string email) {
            this.Email = email;
            this.data = dataAccess;
        }

        public DaSubscriber(INewsletterDataAccess dataAccess, Guid uniqueId) {
            this.data = dataAccess;
            this.instance = new ImpSubscriber("");
            this.instance.Email = this.data.GetSubscriberEmail(uniqueId);
            this.instance.UniqueId = uniqueId;
        }

        #endregion

        #region Methods

        public bool Exist() {
            return this.data.CheckEmailExist(this.Email);
        }

        public bool Save() {
            if (!this.Email.IsValidEmail())
                return false;
            if (!this.data.SaveSubscriber(this.Email, this.UniqueId, CultureInfo.CurrentCulture.Name))
                return false;
            ASyncMail sendMail = new ASyncMail(Factory.Instance().GetASyncMailData(), 1, this.instance, typeof(ImpSubscriber), new MailAddress(this.Email, this.Email), "Subskrypcja newslettera");
            //ASyncMail sendMail = new ASyncMail(Factory.Instance().GetASyncMailData(),1,this.instance,)
            sendMail.Save();
            return true;
        }

        public bool Confirm() {
            if (this.Exist())
                return this.data.Confirm(this.Email);
            else return false;
        }

        public bool Remove() {
            if (this.Exist())
                return this.data.Remove(this.Email);
            else return false;
        }

        #endregion

    }
}
